package org.agridata.akvisualization.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.agridata.akvisualization.doMain.entity.Immunity;
import org.agridata.akvisualization.mapper.ImmunityMapper;
import org.agridata.akvisualization.result.Result;
import org.agridata.akvisualization.service.ImmunityService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ImmunityServiceImpl implements ImmunityService {

    @Autowired
    private ImmunityMapper mapper;

    @Autowired
    private DiseaseSurveillanceServiceImpl dis;

    @Override
    public Result statisticsImmunity() {
        List<Map<String,Object>> list = mapper.statisticsImmunityList();
        Map<String, List<Map<String, Object>>> map = new HashMap<>();
        try {
            for (Map<String, Object> objectMap : list) {
                String type = objectMap.get("type").toString();

                // 检查是否已存在具有相同类型的疾病的列表
                if (map.containsKey(type)) {
                    // 如果存在，则将数据添加到现有列表中
                    map.get(type).add(objectMap);
                } else {
                    // 如果不存在，则创建一个新的列表，并将数据添加到其中
                    List<Map<String, Object>> tempList = new ArrayList<>();
                    tempList.add(objectMap);
                    map.put(type, tempList);
                }
            }
            Map<String, List<Map<String, Object>>> listMap = zhuanyiAnimal(map);
            System.out.println(listMap);
            return Result.ok(listMap);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("出现异常");
        }
    }

    @Override
    public Result defenseImportByCycle(List<Immunity> memberList,String dates ,String category, Integer cycle) {
        int successCount = 0;
        int failureCount = 0;
        try {
            List<Immunity> brucellosisList = mapper.selectImmunityByCategoryAndCycle(dates,category,cycle.toString());
            if (brucellosisList.size() > 0) {
                mapper.deleteImmunity(brucellosisList);
            }
            for (Immunity immunity : memberList) {
                try {
                    immunity.setCategory(category);
                    immunity.setDates(dates);
                    immunity.setCycle(cycle);
                    mapper.insertImmunity(immunity);
                    successCount++;
                } catch (Exception e) {
                    failureCount++;
                    e.printStackTrace();
                }
            }


            return Result.ok("成功：" + successCount + "条" + "，" + "失败" + failureCount + "条");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("出现异常");
        }
    }

    @Override
    public Result selectDefenseList(String category, Integer cycle,Long pageNo,Long pageSize) {
        QueryWrapper<Immunity> queryWrapper = new QueryWrapper<>();
        try {
            if (StringUtils.isNoneBlank(category)){
                queryWrapper.eq("category",category);
            }
            if (StringUtils.isNoneBlank(category)){
                queryWrapper.eq("cycle",cycle);
            }
            IPage<Immunity> page = new Page<>(pageNo,pageSize);
            IPage<Immunity> immunityIPage = mapper.selectPagess(page, category,cycle);

            return Result.ok(immunityIPage);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("出现异常");
        }
    }

    @Override
    public Result updateDefenseById(Immunity immunity) {
        UpdateWrapper<Immunity> updateWrapper = new UpdateWrapper<>();
        try {
            updateWrapper.eq("id",immunity.getId());
            int update = mapper.updateImmunity(immunity);
            return Result.ok(update);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("出现异常！");
        }

    }

    @Override
    public Result progressThisYear() {
        try {
            List<Immunity> immunities = mapper.selectLists();
            //创建一个新的map用以存储分类之后的数据
            Map<String, Map<String,List<Immunity>>> listMap = new HashMap<>();
            //对数据进行春防、秋防分类
            for (Immunity immunity : immunities) {
                //将Category字段内容转为拼音当做key
                String pinyin = dis.toPinyin(immunity.getCategory());
                String bing = dis.toPinyin(immunity.getDiseaseType()+immunity.getAnimalType());
                //验证key是否存在
                if (listMap.containsKey(pinyin)) {
                    //如果存在直接添加对应的key中的list中
                    if(listMap.get(pinyin).containsKey(bing)){
                        listMap.get(pinyin).get(bing).add(immunity);
                    }else {
                        //不存在创建一个新的list并put进map中
                        ArrayList<Immunity> arrayList = new ArrayList<>();
                        arrayList.add(immunity);
                        listMap.get(pinyin).put(bing,arrayList);
                    }
                } else {
                    // 不存在创建一个新的 list 并 put 进 map 中
                    ArrayList<Immunity> arrayList = new ArrayList<>();
                    arrayList.add(immunity);

                    // 创建一个新的 map 存储 bing 对应的 list
                    Map<String, List<Immunity>> bingMap = new HashMap<>();
                    bingMap.put(bing, arrayList);

                    // 将新的 bingMap 放入 listMap 中
                    listMap.put(pinyin, bingMap);
                }
            }
            return Result.ok(listMap);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("出现异常");
        }
    }


    private Map<String, List<Map<String, Object>>> zhuanyiAnimal(Map<String, List<Map<String, Object>>> map) {
        List<Map<String, Object>> scaleList = map.get("scale");
        List<Map<String, Object>> nonscaleList = map.get("nonscale");
        List<Map<String, Object>> scale = new ArrayList<>();
        List<Map<String, Object>> nonscale = new ArrayList<>();
        int totalImmuneCountScale = 0; // scale 中的 禽类immuneCount 总和
        int totalImmuneCountNonscale = 0; // nonscale 中的禽类 immuneCount 总和
        for (Map<String, Object> originVo : scaleList) {
            int animalID = Integer.parseInt(originVo.get("animalID").toString());
            int immuneCount = Integer.parseInt(originVo.get("ImmuneCount").toString());
            if (animalID == 0||animalID==16||animalID==10000||animalID==38||animalID==13
                    ||animalID==99913||animalID==30000||animalID==70000||animalID==4||animalID==43){
                originVo.put("animalName","其它");
                originVo.put("animalID",0);
            }
            if (animalID == 8 || animalID == 7 || animalID == 6 || animalID == 20400 || animalID == 9 || animalID == 29900) {
                originVo.put("animalName","禽");
                originVo.put("animalID",0);
                totalImmuneCountScale += immuneCount;
            }
            scale.add(originVo);
        }
        // 处理 nonscaleList
        for (Map<String, Object> originVo : nonscaleList) {
            int animalID = Integer.parseInt(originVo.get("animalID").toString());
            int immuneCount = Integer.parseInt(originVo.get("ImmuneCount").toString());
            if (animalID == 0 || animalID == 16 || animalID == 10000 || animalID == 38 || animalID == 13
                    || animalID == 99913 || animalID == 30000 || animalID == 70000 || animalID == 4 || animalID == 43) {
                originVo.put("animalName", "其它");
                originVo.put("animalID", 0);
            }
            if (animalID == 8 || animalID == 7 || animalID == 6 || animalID == 20400 || animalID == 9 || animalID == 29900) {
                originVo.put("animalName", "禽");
                originVo.put("animalID", 0);
                totalImmuneCountNonscale += immuneCount;
            }
            nonscale.add(originVo);
        }
        for (Map<String, Object> objectMap : scale) {
            int animalID = Integer.parseInt(objectMap.get("animalID").toString());
            if (animalID == 0) {
                objectMap.put("ImmuneCount", totalImmuneCountScale);
            }
        }
        for (Map<String, Object> objectMap : nonscale) {
            int animalID = Integer.parseInt(objectMap.get("animalID").toString());
            if (animalID == 0) {
                objectMap.put("ImmuneCount", totalImmuneCountNonscale);
            }
        }

        System.out.println(scale);
        System.out.println(nonscale);
        HashMap<String, List<Map<String,Object>>> stringListHashMap = new HashMap<>();
        stringListHashMap.put("scale",scale);
        stringListHashMap.put("nonscale",nonscale);
        return stringListHashMap;
    }
}
